package com.dz.lm.common.util;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Properties;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.dz.lm.common.utils.StringUtils;

@Component
public class SmsSender {
	private static final Logger logger = LoggerFactory.getLogger(SmsSender.class);
	private static InputStream in;
	private static Properties p;

	static {
		try {
			in = SmsSender.class.getClassLoader().getResourceAsStream(
					"sms_info.properties");
			p = new Properties();
			p.load(in);
		} catch (FileNotFoundException e) {
			logger.error("SendSMS Not Found File :sms_info.properties");
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("SendSMS IOException");
			e.printStackTrace();
		}
	}

	/**
	 * 发送短信接口
	 * 
	 * @param phone
	 * @param templateName
	 * @param replaceContent
	 * @return
	 * @throws Exception
	 */
	public String sendSms(String mobilePhone, String content) throws Exception {
		// 发送内容
		String sendUrl = p.getProperty("mlrtUrl");
		String userName = p.getProperty("mlrtUserName");
		String password = p.getProperty("mlrtPWD");
		String apiKey = p.getProperty("mlrtApiKey");
    	String code = null;
    	PostMethod postMethod = new PostMethod(sendUrl);
		try {
			postMethod.getParams().setContentCharset("UTF-8");
			postMethod.addRequestHeader("Connection", "close");
			
			NameValuePair[] data = {
			        new NameValuePair("username", userName),
			        new NameValuePair("password_md5", MD5Util.MD5(password)),
			        new NameValuePair("apikey", apiKey),
			        new NameValuePair("mobile", mobilePhone),
			        new NameValuePair("encode", "UTF-8"),
			        new NameValuePair("content", URLEncoder.encode(content, "utf-8"))
			};
			postMethod.setRequestBody(data);
			HttpClient httpClient = new HttpClient();
			int statusCode = httpClient.executeMethod(postMethod);
			String response = postMethod.getResponseBodyAsString();
			logger.info("MLRTUtil statusCode: " + statusCode + ", body: "+ response);
			
			if(!StringUtils.isEmpty(response)){
				String res[] = response.split(":");
				if("success".equals(res[0])){
					code = "0";
				}else{
					code = "1";
					logger.info("美联软通数据源返回错误"+response);
				}
			}else{
				throw new Exception("美联软通短信返回结果解析错误");
			}
		} catch (Exception e) {
			logger.info("美联软通数据源返回错误" + e.getStackTrace());
			throw new Exception("美联软通数据源返回错误", e);
		} finally {
			// 释放连接
			postMethod.releaseConnection();
		}
        return code;
	}
}
